package one;

import java.util.*;


/**
 * Given an array of strings, return all groups of strings that are anagrams.
 * <p>
 * Note: All inputs will be in lower-case.
 * <p>
 * ================================
 * <p>
 * abcc ccba cbac is anagrams.
 * <p>
 * Complexity : O(n) space O(n)
 * <p>
 * use hashmap to record the string after sort by chars
 */
public class Day04_Anagrams {
    public ArrayList<String> anagrams(String[] strs) {
        ArrayList<String> res = new ArrayList<String>();
        if (strs.length <= 1) {
            return res;
        }
        Map<String, List<Integer>> checks = new HashMap<String, List<Integer>>();

        for (int i = 0; i < strs.length; i++) {
            char[] arrs = strs[i].toCharArray();
            Arrays.sort(arrs);
            String nstr = new String(arrs);
            if (checks.containsKey(nstr)) {
                checks.get(nstr).add(i);
            } else {
                List<Integer> tmps = new ArrayList<Integer>();
                tmps.add(i);
                checks.put(nstr, tmps);
            }
        }
        for (String t : checks.keySet()) {
            List<Integer> tmps = checks.get(t);
            if (tmps.size() <= 1) {
                continue;
            }
            for (Integer index : tmps) {
                res.add(strs[index]);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Day04_Anagrams anagrams = new Day04_Anagrams();
        String[] strs = {"abcc", "ccba", "cbad"};
        ArrayList<String> result = anagrams.anagrams(strs);
        System.out.println(result);

    }
}
